<script setup>
import { onBeforeMount, reactive, ref, toRefs } from 'vue';
import { addPod } from '../../api/pod.js';
import { ElMessage } from 'element-plus'
//定义表单内容
const data = reactive({
  podAddForm: {
    name: "",
    namespace: "",
    image: "",
  }
})
//判定当前是创建还是更新
const props = defineProps({
  method: {
    type: String,
    default: "Create"
  },
  podAddForm: {
    type: Object
  }
})

//解构表单内容
const { podAddForm } = toRefs(data)

const podFormRef = ref()
const loading = ref(false)

const emits = defineEmits(["roolback"])

// //创建一个回调函数，将data中的数据赋值给props
// onBeforeMount(()=>{
//   data.podAddForm = JSON.parse(JSON.stringify(props.podAddForm))
// })

//定义清空输入框方法
const clear = ()=> {
  podFormRef.value.resetFields()
}
//定义需要校验的表单数据
const rules = reactive({
  name:[
    { required: true, message: 'Pod名称不能为空',trigger: 'blur'}
  ],
  namespace:[
    { required: true, message: '命名空间不能为空',trigger: 'blur'}
  ],
  image:[
    { required: true, message: '镜像地址不能为空',trigger: 'blur'}
  ],
})
const submit = () => {
  podFormRef.value.validate((valid) => {
    if (valid) {
      // 表单校验成功，执行调用接口
      loading.value = true
      addPod(props.podAddForm).then((response) => {
        ElMessage({
          message: response.data.message,
          type: 'success'
        })
        emits('roolback')
        loading.value = false // 修复：应该是 false
      }).catch((error) => {
        // 添加错误处理
        ElMessage({
          message: '操作失败: ' + (error.message || ''),
          type: 'error'
        })
        loading.value = false
      })
    } else {
      // 表单校验失败，显示提示信息
      ElMessage({
        message: "请完善表单内容",
        type: 'warning'
      })
    }
  })
}

</script>

<template>
    <el-form :rules="rules" ref="podFormRef" :model="podAddForm">
      <el-form-item class="form-item" prop="name" label="Pod名称" label-width="100px">
        <el-input v-model="podAddForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item class="form-item" prop="namespace" label="namespace" label-width="100px">
        <el-input v-model="podAddForm.namespace" autocomplete="off" />
      </el-form-item>
      <el-form-item class="form-item" prop="image" label="image" label-width="100px">
        <el-input v-model="podAddForm.image" autocomplete="off" />
      </el-form-item>
    </el-form>
    <span style="display: block;" margin-top:30px  class="span-button">
      <el-button @click="clear">清空</el-button>
      <el-button @click="submit">
        {{ props.method=="Create"?"提交":"更新" }}
      </el-button>
    </span>
</template>

<style scoped>
.form-item{
  width: 70%;
  margin: 15px auto;
}
</style>
